<template>
  <!--
  用户管理页面（商家）
  -->
  <div class="table-classic-wrapper1">
    <el-card shadow="always">

      <!-- 查询栏 -->
      <el-form
          ref="searchForm"
          :inline="true"
          :model="searchForm"
          :rules="searchRules"
          label-width="90px"
          class="search-form">
        <el-form-item prop="rate">
          <el-input placeholder="请输入餐厅等级" v-model="searchForm.rate" style="width: 240px;">
            <i slot="suffix" class="el-input__icon el-icon-search"
               @click="onSubmit"></i>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="danger" @click="fetchAllMerchantByPagination">获取全部餐厅</el-button>
        </el-form-item>
      </el-form>

      <!--
      selection-change：当选择项发生变化时会触发该事件
      -->
      <el-table
          ref="userTable"
          :data="userData"
          style="width: 100%;"
          :header-cell-style="{textAlign: 'center'}"
          @selection-change="handleSelectionChange"
          stripe
          :cell-style="{textAlign: 'center'}"
          class="table-inline-edit">

        <el-table-column type="selection" width="50"/>

        <el-table-column
            prop="id"
            label="编号">
        </el-table-column>

        <el-table-column
            prop="userName"
            label="餐厅名称">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>餐厅名称: {{ scope.row.userName }}</p>
              <p>手机: {{ scope.row.telephone }}</p>
              <p>营业执照编号：{{ scope.row.account }}</p>
              <div slot="reference">
                <el-tag size="medium">{{ scope.row.userName }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>

        <el-table-column
            prop="sex"
            label="性别">
          <template slot-scope="scope">
            <span v-if="scope.row.sex===0">男</span>
            <span v-if="scope.row.sex===1">女</span>
          </template>
        </el-table-column>

        <el-table-column
            prop="telephone"
            label="手机号">
        </el-table-column>

        <el-table-column
            prop="address"
            label="城市">
        </el-table-column>

        <el-table-column
            prop="account"
            label="营业执照编号">
        </el-table-column>

        <el-table-column label="餐厅等级">
          <template slot-scope="scope">
            <el-rate
                v-model="scope.row.rate"
                disabled
                show-score
                text-color="#ff9900">
            </el-rate>
          </template>
        </el-table-column>

        <el-table-column
            label="操作"
            width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="primary"
                       @click="handleEdit(scope.row)">编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <Pagination :total="total" :page="currentPage" :limit="pageSize" @pagination="handlePageChange"></Pagination>

      <!--
      新增/编辑 弹出栏
      visible：是否显示 Dialog，支持.sync修饰符
      -->
      <el-dialog
          title="编辑"
          :visible.sync="formVisible"
          width="30%"
          class="dialog-form"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :before-close="handleClose">
        <el-form
            ref="updateForm"
            :model="updateForm"
            label-width="100px">

          <el-rate
              v-model="updateForm.rate"
              show-score
              text-color="#ff9900">
          </el-rate>

          <div class="footer-item">
            <el-button @click="cancelForm">取 消</el-button>
            <el-button type="primary" @click="submitForm('updateForm')">确 定</el-button>
          </div>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {getDefinedMerchant, getAllMerchantByPagination, getMrchantByRate} from "@/api/administration/user";
import Pagination from "@/component/pagination/Pagination";

export default {
  name: "AdministratorUser",
  components: {Pagination},

  data() {
    return {
      /**
       * userData：存储注册用户的有关信息的数组
       */
      userData: [],

      /**
       * 更新列表
       */
      updateForm: {
        id: undefined,
        rate: undefined
      },

      /*
      * 查询列表
      */
      searchForm: {
        rate: "",
      },

      /*
      * 数据总条数
      */
      total: 0,

      /**
       * currentPage：当前页面
       */
      currentPage: 0,

      /**
       * pageSize：页面大小
       */
      pageSize: 8,

      /*
      * 多选数据暂存数组
      */
      multipleSelection: [],

      /*
      * 新增/编辑 弹出框显示/隐藏
      */
      formVisible: false,

      searchRules: {
        rate: [{
          pattern: /^\d+$/,
          message: '请输入整数'
        }],
      },

    }
  },

  methods: {

    /*
    * 多选操作，与multipleSelection相对应
    * 该功能在管理员页面没有实际作用
    */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    /**
     * before-close：关闭前的回调，会暂停Dialog的关闭
     * 编辑弹出框，关闭时操作
     */
    handleClose() {
      this.formVisible = false;
    },

    /**
     * 处理分页
     */
    handlePageChange(val) {
      this.currentPage = val.page;
      this.fetchAllMerchantByPagination();
    },

    /**
     * 编辑表单提交
     */
    submitForm(formName) {
      this.$refs[formName].validate(valid => {

        const formData=new FormData();
        formData.append("id",this.updateForm.id);
        formData.append("rate",this.updateForm.rate);

        if (valid) {
          this.updateDefinedMerchant(formData);
          this.formVisible = false
        } else {
          return false
        }
      })
    },

    /*
     * 编辑表单取消提交
     */
    cancelForm() {
      this.formVisible = false;
    },

    /**
     * 打开编辑窗口
     */
    handleEdit(row) {
      this.formVisible = true;
      this.updateForm.id = row.id;
      this.updateForm.rate = row.rate;
    },

    /**
     * 页面初始化时获取全部餐厅（实现分页）
     */
    fetchAllMerchantByPagination() {

      const formData = new FormData();
      formData.append("currentPage", this.currentPage);
      formData.append("pageSize", this.pageSize);

      getAllMerchantByPagination(formData).then(res => {
        this.userData = res.message;
        this.total = res.total;
      }).catch(() => {
        this.$message({
          message: "error",
          type: "error"
        })
      })
    },

    /**
     * 修改指定商家用户的信息
     */
    updateDefinedMerchant(data) {
      getDefinedMerchant(data).then(res => {
        if(res.information === 1){
          this.$message.success("更新成功");
          this.fetchAllMerchantByPagination()
        }else{
          this.$message.error("更新失败");
        }
      }).catch(() => {
        this.$message({
          message: "error",
          type: "error"
        })
      })
    },

    /**
     * 根据rate查询餐厅
     */
    onSubmit() {

      const formData=new FormData();

      formData.append("rate", this.searchForm.rate);
      formData.append("currentPage", this.currentPage);
      formData.append("pageSize", this.pageSize);

      if (this.searchForm.rate === "") {
        this.$message.warning("请输入餐厅等级");
        this.userData = [];
        this.total = 0;
      } else if (this.searchForm.rate < '1' || this.searchForm.rate > '5') {
        this.$message.warning("请输入1-5之间的整数");
        this.userData = [];
        this.total = 0;
      } else {
        this.$refs.searchForm.validate(valid => {
          if (valid) {
            getMrchantByRate(formData).then(res => {
              this.userData = res.message;
              this.total = res.total;
            }).catch(() => {
              this.$message({
                message: "error",
                type: "error"
              })
            })
          } else {
            this.$message.warning("请输入整数");
            this.userData = [];
            this.total = 0;
          }
        })

      }
    },
  },

  created() {
    this.fetchAllMerchantByPagination();
  }
}
</script>

<style lang="less">
@import "../../../assets/less/aministration/merchant/cardMerchant.less";
</style>